package com.yuer.zk.zk;

import io.netty.util.CharsetUtil;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import static org.apache.zookeeper.CreateMode.EPHEMERAL_SEQUENTIAL;

public class ZkGetNodeTest implements Watcher {

    static CountDownLatch countDownLatch = new CountDownLatch(1);
    private  static ZooKeeper zooKeeper;
    public static void main(String[] args) {
        try {
              zooKeeper =  new ZooKeeper("192.168.56.103:2182",5000,new ZkGetNodeTest());
            System.out.println("此时的链接状态：  "+zooKeeper.getState());
            Thread.sleep(Integer.MAX_VALUE);
            System.out.println("此时的链接状态---->：  "+zooKeeper.getState());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {

        if(event.getState() == Event.KeeperState.SyncConnected){
            countDownLatch.countDown();
            System.out.println("方法执行中....."+event.getState());
        }
        if(event.getType() == Event.EventType.NodeChildrenChanged){
            System.out.println("当子节点发生改变的时候....."+event.getType());
        }
        createNodeData();
    }
    private void createNodeData(){
        try {
            byte[] result_test_persistent = zooKeeper.getData("/zok-test—persistent",true,null);
            System.out.println("test—persistent: " + new String(result_test_persistent, CharsetUtil.UTF_8));


           List<String> stringList = zooKeeper.getChildren("/zok-test—persistent",true);
            System.out.println(stringList);


        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
